<?php

namespace App\Http\Controllers;

use App\Events\TransSqlEevent;
use App\Services\Tcc\Process\Process;
use Ethansmart\HttpBuilder\Builder\HttpClientBuilder;
use Illuminate\Http\Request;
use App\Models\User;
use DB;
use App\TransactionSql;

class TccController extends Controller
{
    protected $tccProcess ;

    function __construct(Process $tccProcess)
    {
        $this->tccProcess = $tccProcess;
    }

    /**
     * TCC try 方法
     * @method get
     */
    public function tccTry()
    {
//        $this->listen();
        /*$data = [
            [
                'uri'=>'http://mobile.weather.com.cn/data/forecast/101010100.html?_=1381891660081',
                'data'=>[]
            ]
        ];

        return $this->tccProcess->processTry($data);
        */
//        $event = new TransSqlEevent();
//        event(new TransSqlEevent());

        DB::connection()->enableQueryLog();
        DB::beginTransaction();
        $u = new User();
        $u->name = "Ethan";
        $u->save();

        User::get();
//      User::get();
      DB::commit();

        $queries = DB::getQueryLog();
        dd($queries);

    }

    public function listen()
    {
        DB::listen(function($event) {
            $LOG_TABLE_NAME = 'log';
            $query  = str_replace("?", "'%s'", $event->sql);
            $query = vsprintf($query, $event->bindings);
            if(stripos($query, 'insert into `'.$LOG_TABLE_NAME.'`')===false){
                $sql = new TransactionSql();
                $sql->sql = json_encode($event->sql);
                $sql->server = "res_ms";
//                $sql->save();
            }

        });
    }
}
